﻿#ifndef GL_WIDGET_H_
#define GL_WIDGET_H_

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QImage>
#include "JZGLCamera.h"
#include "JZGLScene.h"
#include "JZGLItem.h"

class JZGLView : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    JZGLView(QWidget* parent = nullptr);
    ~JZGLView();

    JZGLCamera* camera();

    void setScene(JZGLScene* scene);
    JZGLScene* scene();

    void setViewport(int x,int y,int w,int h);
    void updateItemBuffer();

    QPoint worldToPixel(QVector3D world);
    QVector3D pixelToWorld(QPoint pt);
    float getDepth(int x, int y);

protected:
    void initializeGL() override;
    void resizeGL(int w, int h) override;
    void paintGL() override;

private:

    virtual void mousePressEvent(QMouseEvent* e) override;
    virtual void mouseMoveEvent(QMouseEvent* e) override;
    virtual void mouseReleaseEvent(QMouseEvent* e) override;

    virtual void keyPressEvent(QKeyEvent* event) override;
    virtual void keyReleaseEvent(QKeyEvent* event) override;

    void initShaders();
    void drawMeshItems();
    void drawLineItems();
    void draw3DItems();
    void draw2DItems();

    QVector<float> vertexToFloat(const QVector<VertexData>& points);

    QOpenGLShaderProgram m_program;
    JZGLCamera m_camera;
    JZGLScene* m_scene;

    QOpenGLBuffer m_meshBuffer;
    QOpenGLBuffer m_meshIndexBuffer;

    QOpenGLBuffer m_lineBuffer;
    QOpenGLBuffer m_lineIndexBuffer;
    QMatrix4x4 m_worldModel;

    double m_highDpi;
    QPoint m_mouseDownPos;
    bool m_mouseDown;
};

#endif // !GL_WIDGET_H_